package com.piece.core.pay.client.impl.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.framework.util.time.DateUtil;
import com.piece.core.pay.dto.PayOrderUnifiedReqDTO;
import com.piece.core.pay.enums.PayChannelType;
import lombok.extern.slf4j.Slf4j;
import java.util.Objects;

/**
 * 支付宝手机网页支付实现类
 * <p>文档：https://opendocs.alipay.com/apis/api_1/alipay.trade.wap.pay</p>
 */
@Slf4j
public class AliPayWapPayClient extends AbstractAliPayClient {

    public AliPayWapPayClient(String channelId, AliPayClientConfig config) {
        super(channelId, PayChannelType.ALIPAY_WAP.getCode(), config, new AliPayResponseMapping());
    }

    @Override
    public AjaxResponse doUnifiedOrder(PayOrderUnifiedReqDTO reqDTO) {
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(reqDTO.getMerchantOrderId());
        model.setSubject(reqDTO.getSubject());
        model.setBody(reqDTO.getBody());
        model.setTotalAmount(calculateAmount(reqDTO.getAmount()).toString());
        model.setProductCode("QUICK_WAP_PAY");
        model.setTimeExpire(DateUtil.formatDate(reqDTO.getExpireTime(), "yyyy-MM-dd HH:mm:ss"));

        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setBizModel(model);
        request.setNotifyUrl(StringUtil.isNotEmpty(config.getNotifyUrl()) ? config.getNotifyUrl() : reqDTO.getNotifyUrl());
        request.setReturnUrl(StringUtil.isNotEmpty(config.getReturnUrl()) ? config.getReturnUrl() : reqDTO.getReturnUrl());

        // 执行请求
        AlipayTradeWapPayResponse response;
        try {
            response = client.pageExecute(request);
        } catch (AlipayApiException e) {
            log.error("[支付宝wap支付发起支付失败]：{}", e);
            return AjaxResponse.error("支付宝wap支付发起支付失败");
        }

        if (response.isSuccess() && Objects.isNull(response.getCode()) && Objects.nonNull(response.getBody())) {
            return AjaxResponse.result(codeMapping.apply("10000", "Success"), response);
        } else {
            return AjaxResponse.result(codeMapping.apply(response.getCode(), response.getMsg()), response);
        }
    }
}
